//
//  CCVSCorePlotGraphView.m
//  ClinicalCollections
//
//  Created by Pasirstein, David B on 5/2/13.
//  Copyright (c) 2013 GOPI. All rights reserved.
//

#import "CCVSCorePlotGraphView.h"
#import "CCVSCommon.h"
#import "CommonAPI.h"
#import "CCVSGraphData+Utilities.h"

@interface CCVSCorePlotGraphView () {

    CPTXYGraph *graph, *barChart, *pieGraph;
    CPTPieChart *piePlot;
    BOOL piePlotIsRotating;
}

@property (weak,nonatomic) UIViewController <CCVSCustomViewDelegate> * vc;

@end

@implementation CCVSCorePlotGraphView

@synthesize data = _data;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}


-(BOOL)isExpandable //will return if the view should support dyanamic resizing
{
    return NO;
}

//should return the frame size with width and height populated
+(CGSize)calcViewHeight:(CGFloat)viewWidth fromObject:(id<CCVSCustomDataType>)data
{
    // 218 x 179 for outer
    //we want the graph to be 185 width by 122 height
    
    CGSize size;
    if (viewWidth >= 240) {
        viewWidth = 240;
    }
    //we have less space so we need to be smaller
    size = CGSizeMake(viewWidth,
                      (viewWidth / 1.2)+CCVS_BOARDERSIZE*2);
    return size;
}

//initialize the object...primary way it will be init'ed
-(id)initWithData:(id<CCVSCustomDataType>)data withFrame:(CGRect)frame viewController:(UIViewController*)vc
{
    CGRect newFrame = frame;
    /// we know better and really want to be centered in the view space
    if (frame.size.width >= 240) {
        CGSize viewSize = CGSizeMake(240, 240/1.2);
        CGPoint xy = [CCVSCorePlotGraphView centerInView:viewSize inView:frame.size];
        newFrame = CGRectMake(xy.x, xy.y, viewSize.width, viewSize.height);
    }
    self = [super initWithFrame:newFrame];
    ///
    self.data = data;
    self.vc = (UIViewController <CCVSCustomViewDelegate> *)vc;
    self.autoresizesSubviews = YES;
    self.opaque = YES;
    self.clearsContextBeforeDrawing = YES;
    self.userInteractionEnabled = YES;
    self.backgroundColor = [UIColor whiteColor];
    return self;
}

//should build view to be displayed (would likely return self)
-(UIView*)buildView
{
    if ([((CCVSGraphData*)self.data).chartType isEqualToString:BAR_CHART]) {
        [self constructBarChart:self];
    }
    else if ([((CCVSGraphData*)self.data).chartType isEqualToString:PIE_CHART]) {
        [self constructPieChart:self];
    }
    
    // when we are tapped, we should segue to the zoomed in view
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGestureForGraph:)];
    tap.numberOfTapsRequired = 1;
    [self addGestureRecognizer:tap];
    
    return self;
}

-(BOOL)willSegueOnEvent //true/false if the view will require a segue
{
    return YES;
}

-(void)handleTapGestureForGraph:(UITapGestureRecognizer*)gesture
{
    //NSLog(@"Tap captured: %@",gesture);
    [self.vc segueToVCWith:self.data segueName:[self nameOfSegue:gesture]];
}

//if true above this should return the name of the segue
//if this was requested as a result of a gesture event
//the gesture will be provided as well
-(NSString*)nameOfSegue:(UIGestureRecognizer*)gesture
{
    return @"showDetail";
}


+(CGPoint)centerInView:(CGSize)viewSize inView:(CGSize)inViewSize
{
    CGPoint xy = CGPointMake(0, 0);
    //CGSize inViewSize = inView.frame.size;
    //CGSize viewSize = view.frame.size;
    
    xy.x = (inViewSize.width / 2) - (viewSize.width / 2);
    xy.y = (inViewSize.height / 2) - (viewSize.height / 2);
    
    return xy;
}


-(void)constructPieChart:(CPTGraphHostingView *) hostingView
{
    // Create pieChart from theme
    pieGraph = [[CPTXYGraph alloc] initWithFrame:CGRectZero];
    CPTTheme *theme = [CPTTheme themeNamed:kCPTDarkGradientTheme];
    [pieGraph applyTheme:theme];
    hostingView.hostedGraph             = pieGraph;
    pieGraph.plotAreaFrame.masksToBorder = NO;
    
    pieGraph.paddingLeft   = hostingView.frame.size.width/20;
    pieGraph.paddingTop    = hostingView.frame.size.height/20;
    pieGraph.paddingRight  = hostingView.frame.size.width/20;
    pieGraph.paddingBottom = hostingView.frame.size.height/20;
    
    pieGraph.axisSet = nil;
   
    
    // Prepare a radial overlay gradient for shading/gloss
    CPTGradient *overlayGradient = [[CPTGradient alloc] init];
    overlayGradient.gradientType = CPTGradientTypeRadial;
    overlayGradient              = [overlayGradient addColorStop:[[CPTColor blackColor] colorWithAlphaComponent:0.0] atPosition:0.0];
    overlayGradient              = [overlayGradient addColorStop:[[CPTColor blackColor] colorWithAlphaComponent:0.3] atPosition:0.9];
    overlayGradient              = [overlayGradient addColorStop:[[CPTColor blackColor] colorWithAlphaComponent:0.7] atPosition:1.0];
    // Add pie chart
    piePlot                 = [[CPTPieChart alloc] init];
    piePlot.title = @"XYZ";
    piePlot.dataSource = (CCVSGraphData*)self.data;
    piePlot.delegate = (CCVSGraphData*)self.data;
    piePlot.pieRadius       = hostingView.frame.size.width/8;
    piePlot.identifier      = @"Therapy";
    piePlot.startAngle      = M_PI_4;
    piePlot.sliceDirection  = CPTPieDirectionCounterClockwise;
    piePlot.borderLineStyle = [CPTLineStyle lineStyle];
    piePlot.labelOffset     = 0;
    piePlot.overlayFill     = [CPTFill fillWithGradient:overlayGradient];
    [pieGraph addPlot:piePlot];
}

-(void)constructBarChart:(CPTGraphHostingView *) hostingView;
{
    
    // Create barChart from theme
    barChart = [[CPTXYGraph alloc] initWithFrame:CGRectZero];
    
    CPTTheme *theme = [CPTTheme themeNamed:kCPTDarkGradientTheme];
    [barChart applyTheme:theme];
    hostingView.hostedGraph             = barChart;
    barChart.plotAreaFrame.masksToBorder = NO;
    barChart.paddingLeft   = hostingView.frame.size.width/20;
    barChart.paddingTop    = hostingView.frame.size.height/20;
    barChart.paddingRight  = hostingView.frame.size.width/20;
    barChart.paddingBottom = hostingView.frame.size.width/10;
    
    // Need to set ranges from data for the graph to look nice
    
    float  xMax, yMax;
    xMax = yMax = 0.0f;
    
    Class cls = [CommonAPI class];
    NSArray *arrayData = [CCVSGraphData removeTotalFromArray:((CCVSGraphData*)self.data).chartArray];
    
    for (int i = 0; i < arrayData.count; i++)
        if ([((NSNumber *)[cls getValue:i graphDataArray:arrayData]) floatValue] > yMax)
            yMax = [((NSNumber *)[cls getValue:i graphDataArray:arrayData]) floatValue];
    
    CPTXYPlotSpace *plotSpace;
    
    plotSpace = (CPTXYPlotSpace *)barChart.defaultPlotSpace;
    
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0f) length:CPTDecimalFromFloat(yMax *1.5)];
    
    CPTXYAxisSet *axisSet         = (CPTXYAxisSet *)barChart.axisSet;
    CPTXYAxis *x                  = axisSet.xAxis;
    x.axisLineStyle               = nil;
    x.majorTickLineStyle          = nil;
    x.minorTickLineStyle          = nil;
    x.majorIntervalLength         = CPTDecimalFromString(@"5");
    x.orthogonalCoordinateDecimal = CPTDecimalFromString(@"0");
    x.title                       = @"";
    x.titleLocation               = CPTDecimalFromFloat(7.5f);
    x.titleOffset                 = hostingView.frame.size.width/10;
    x.labelRotation               = M_PI / 4;
    x.labelingPolicy              = CPTAxisLabelingPolicyNone;
    
    NSMutableArray *treatmentLabels = [[NSMutableArray alloc] initWithCapacity:MAX_CAPACITY];
    
    for (int i = 0; i < arrayData.count; i++)
        [treatmentLabels addObject:[cls getGroup:i graphDataArray:arrayData]];
    
    NSArray *xAxisLabels         = [NSArray arrayWithArray:treatmentLabels];
    NSUInteger labelLocation     = 0;
    NSMutableArray *customLabels = [NSMutableArray arrayWithCapacity:[xAxisLabels count]];
    
    NSMutableArray *customTickLocationsArray = [[NSMutableArray alloc] initWithCapacity:MAX_CAPACITY];
    
    // Add number of categories - Treatment labels  in graph
    for (int i = 0; i < xAxisLabels.count; i++)
        if(!i)
            [customTickLocationsArray addObject:[NSDecimalNumber numberWithInt:1]];
        else
            [customTickLocationsArray addObject:[NSDecimalNumber numberWithInt:i*5]];
    
    
    xMax = xAxisLabels.count * 5;
    
    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0f) length:CPTDecimalFromFloat(xMax)];
    NSArray *customTickLocations = [NSArray arrayWithArray:customTickLocationsArray];
    
    for ( NSNumber *tickLocation in customTickLocations ) {
        CPTMutableTextStyle *textStyle = [[CPTMutableTextStyle alloc] init];
        textStyle.fontName = @"Arial";
        textStyle.fontSize = hostingView.frame.size.width/40.0;
        if (textStyle.fontSize < 8)
            textStyle.fontSize = 8;
        textStyle.color = [CPTColor whiteColor];
        CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText:[xAxisLabels objectAtIndex:labelLocation] textStyle:textStyle];
        labelLocation++;
        newLabel.tickLocation = [tickLocation decimalValue];
        newLabel.offset       = x.labelOffset + x.majorTickLength;
        newLabel.rotation     = M_PI / 8;
        [customLabels addObject:newLabel];
    }
    
    x.axisLabels = [NSSet setWithArray:customLabels];
    
    CPTXYAxis *y = axisSet.yAxis;
    y.axisLineStyle               = nil;
    y.majorTickLineStyle          = nil;
    y.minorTickLineStyle          = nil;
    y.majorIntervalLength         = CPTDecimalFromFloat(0.0f);
    y.orthogonalCoordinateDecimal = CPTDecimalFromString(@"0");
  
    // First bar plot
    CPTBarPlot *barPlot = [CPTBarPlot tubularBarPlotWithColor:[CPTColor redColor] horizontalBars:NO];
    barPlot.baseValue  = CPTDecimalFromString(@"0");
    barPlot.dataSource = (CCVSGraphData*)self.data;
    barPlot.delegate = (CCVSGraphData*)self.data;
    barPlot.barOffset  = CPTDecimalFromFloat(0.750f); 
    barPlot.identifier = @"Bar Plot 1";
    
    [barChart addPlot:barPlot toPlotSpace:plotSpace];
    
    //[plotSpace scaleToFitPlots:barChart.allPlots];
}




/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
